<?php

namespace app\controller\open;

use app\BaseController;
use app\model\Merchant;
use app\model\MerchantBalance;
use app\model\StationBasic;
use app\model\StationOil;
use app\model\StationOrder;
use app\model\SupplierStation;
use think\facade\Cache;
use think\Response;
use yly_print\YlyOpen;

class Payment extends BaseController
{
    public function discount(): Response
    {
        return $this->success($this->mathDiscount()['discount']);
    }

    public function create(): Response
    {
        $supplier = $this->request->supplier;
        $orderModel = $this->app->make(StationOrder::class);
        $orderIts = $orderModel->where('supplier_sn', $this->request->param('out_order_sn'))->where('supplier', $supplier['id'])->find();
        if (!empty($orderIts)) {
            return $this->success([
                "order" => $orderIts->order_sn,
                "out_order_sn" => $orderIts->supplier_sn,
                "money" => $orderIts->money
            ]);
        }
        if (Cache::has('order_' . $this->request->param('out_order_sn'))) throw new \Exception('重复提交订单！', 6004);
        Cache::set('order_' . $supplier['id'] . '_' . $this->request->param('out_order_sn'), true, 30);
        $dat = $this->mathDiscount();
        $discount = $dat['discount'];
        $station = $dat['station'];
        $oil = $dat['oil'];
        $sup = $dat['sup'];
        if ($supplier['type'] == 1 && $supplier['balance'] < $discount['discount_money']) throw new \Exception("余额不足！", 6005);
        if ($supplier['type'] == 2 && $supplier['forzen'] < $discount['discount_money']) throw new \Exception("当前支付金额已超过系统预授权金额！", 6005);

        if ($supplier['type'] == 1 || $supplier['type'] == 2) {
            $supplier->inc($supplier['type'] == 1 ? 'forzen' : 'balance', $discount['discount_money'])->dec($supplier['type'] == 1 ? 'balance' : 'forzen', $discount['discount_money'])->save();
        }
        $param = $this->request->post();
        $prices = ["sat_price", "mon_price", "tue_price", "wed_price", "thu_price", "fri_price", "sat_price"][date("w")];
        $sett_money = mathSettMoney($discount['litter'], $discount['money'], $station['settlement_type'], $station['settlement_money'], $oil[$prices] > 0 ? $oil[$prices] : $oil['default_price'], $oil['gun_price'], $oil['rate_unit']);
        //第三方商家需要提交商家订单
        if ($station['mer_id'] > 0) {
            //冻结商家金额
            $merchant = $this->app->make(Merchant::class)->where('id', $station['mer_id'])->find();
            if ($merchant['balance'] < $sett_money) throw new \Exception("商家余额不足！", 6005);
            $this->app->make(Merchant::class)->where('id', $station['mer_id'])->dec("balance", $sett_money)->inc("disable_balance", $sett_money)->save();
        }
        //生成订单
        $order = [
            "order_sn" => setOrderSn(),
            "supplier_sn" => $param['out_order_sn'],
            "third_info" => $param['user_phone'],
            "pay_type" => "third",
            "amount" => $discount['money'],
            "money" => $discount['discount_money'],
            "discount" => $discount['discount'],
            "gun_price" => $oil['gun_price'],
            "gun_discount" => $station[$prices] > 0 ? $station[$prices] : $station['default_price'],
            "supplier_discount" => $sup["$oil[oil]_rate"] > 0 ? $sup["$oil[oil]_rate"] : $sup['def_rate'],
            "ser_money" => $discount['ser_money'],
            "litter" => $discount['litter'],
            "supplier_money" => $discount['discount_money'],
            "merchant_money" => $sett_money,
            "station_id" => $station['id'],
            "oil" => $oil['oil_name'],
            "gun" => $param['gun'],
            "supplier" => $supplier['id'],
            "state" => 0,
            "gun_unit" => $oil['rate_unit'] == 1 ? "" : "%"
        ];
        $orderModel->save($order);
        Cache::delete("order_" . $supplier['id'] . '_' . $order['supplier_sn']);
        return $this->success(['order' => $order['order_sn'], "out_order_sn" => $order['supplier_sn'], "money" => $order['money']]);
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $supplier = $this->request->supplier;
        $order = $this->app->make(StationOrder::class)->with(['station'])->where('order_sn', $param['order'])->where('state', 0)->where('supplier', $supplier['id'])->find();
        if (empty($order)) throw new \Exception("订单不存在！", 6006);
        $station = $order['station'];
        if ($station['mer_id'] > 0) {
            //确认加油订单扣减油站余额
            $tot = $this->app->make(Merchant::class)->where('id', $station['mer_id'])->find();
            $totOld = bcadd($tot->disable_balance, $tot->balance, 2);
            $tot->dec("disable_balance", $order['merchant_money'])->save();
            $new_money = bcsub($totOld, $order['merchant_money'], 2);
            //余额动账
            (new MerchantBalance)->save([
                "mer_id" => $station['mer_id'],
                "order_sn" => $order['order_sn'],
                "content" => $station['name'] . "油站加油付款",
                "money" => $order['merchant_money'],
                "old_money" => $totOld,
                "new_money" => $new_money,
                "type" => 2,
                "des" => 5
            ]);
        }
        $order->startTrans();
        $order->save(['state' => 1, 'payment_time' => date("Y-m-d H:i:s")]);
        if ($supplier['type'] == 1) $supplier->dec("forzen", $order['money'])->save();
        if ($supplier['type'] == 2) $supplier->dec("balance", $order['money'])->save();
        $order->commit();
        if (!empty($station['print_sn'])) {
            //打印订单
            $this->app->make(YlyOpen::class, ['id' => $station['print_sn'], 'token' => $station['print_key']])->printStation($station['print_sn'], [
                "station" => $station['name'],
                "order_sn" => $order['order_sn'],
                "date" => $order->payment_time,
                "gun_name" => $order['gun'],
                "oil_name" => $order['oil'],
                "money" => $order['amount']
            ]);
        }

        return $this->success(['order' => $order['order_sn'], 'payment_time' => $order->payment_time]);
    }

    public function refund(): Response
    {
        $supplier = $this->request->supplier;
        $param = $this->request->post();
        $order = $this->app->make(StationOrder::class)->with(['station'])->where('order_sn', $param['order'])->where('state', 1)->where('supplier', $supplier['id'])->find();
        if (empty($order)) throw new \Exception("订单不存在！", 6006);
        $order->save([
            "state" => 3,
            "refund_state" => 1,
            "refund_remark" => $param['reason'],
            "refund_sn" => setOrderSn("R")
        ]);
        return $this->success([
            "refund_sn" => $order->refund_sn
        ]);
    }

    public function detail(): Response
    {
        $supplier = $this->request->supplier;
        $param = $this->request->param();
        if (empty($param['order']) && empty($param['out_order_sn'])) throw new \Exception("参数错误！", 4095);
        $order = $this->app->make(StationOrder::class)->with(['station'])->where('supplier', $supplier['id'])->when(!empty($param['order']), function ($query) use ($param) {
            $query->where('order_sn', $param['order']);
        })->when(!empty($param['out_order_sn']), function ($query) use ($param) {
            $query->where('supplier_sn', $param['out_order_sn']);
        })->find();
        if (empty($order)) throw new \Exception("订单不存在！", 6006);

        return $this->success([
            'order' => $order['order_sn'],
            'out_order_sn' => $order['supplier_sn'],
            'amount' => $order['amount'],
            'money' => $order['money'],
            'discount' => $order['discount'],
            'ser_money' => $order['ser_money'],
            'litter' => $order['litter'],
            'station_id' => $order['station']['number'],
            "station_name" => $order['station']['name'],
            'oil' => $order['oil'],
            'gun' => $order['gun'],
            "state" => $order['state'],
            "create_time" => $order['create_time'],
            "payment_time" => $order['payment_time']
        ]);
    }

    protected function mathDiscount(): array
    {
        $post = $this->request->post();
        $supplier = $this->request->supplier;
        //获取油站
        $station = $this->app->make(StationBasic::class)->where('number', $post['station_id'])->where('state', 1)->find();
        if (empty($station)) throw new \Exception("油站不存在！", 6001);
        $oil = $this->app->make(StationOil::class)->where("oil", $post['oil'])->where("station_id", $station['id'])->find();
        if (empty($oil)) throw new \Exception("油品不存在！", 6002);
        $discount = $this->app->make(SupplierStation::class)->where('station_id', $station['id'])->where('supplier_id', $supplier['id'])->find();
        if (empty($discount)) throw new \Exception("油站未授权！", 6003);
        return [
            "discount" => mathSupplierDiscount($station, $oil, $discount, $post['money']),
            "station" => $station,
            "oil" => $oil,
            "sup" => $discount
        ];
    }
}
